package com.ctrip.ec.api.mobile.service.payment;

import com.ctrip.ec.biz.dao.agent.AgentDao;
import com.ctrip.ec.biz.entity.agent.AgentEntity;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;

import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.google.common.cache.CacheBuilder;

import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.loadtime.Agent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * Created by jiangzy on 2018/11/23.
 */
@Service
public class AgentWxPayServiceCache {

    @Autowired
    private AgentDao agent;

    private LoadingCache<Long, Optional<WxPayService>> wxPayServiceCache = CacheBuilder.newBuilder()
            .maximumSize(500).refreshAfterWrite(30, TimeUnit.SECONDS)
            .build(new CacheLoader<Long, Optional<WxPayService>>() {
                @Override
                public Optional<WxPayService> load(Long agentId) throws Exception {

                    AgentEntity agentEntity = agent.entity(agentId);
                    if(agentEntity == null){
                        return Optional.ofNullable(null);
                    }else{
                        WxPayConfig payConfig = new WxPayConfig();
                        payConfig.setAppId(StringUtils.trimToNull(agentEntity.getAppId()));
                        payConfig.setMchId(StringUtils.trimToNull(agentEntity.getMchId()));
                        payConfig.setMchKey(StringUtils.trimToNull(agentEntity.getMchKey()));

                        // 可以指定是否使用沙箱环境
                        payConfig.setUseSandboxEnv(false);

                        WxPayService wxPayService = new WxPayServiceImpl();
                        wxPayService.setConfig(payConfig);
                        return Optional.of(wxPayService);
                    }
                }
            });

    public WxPayService wxPayService(Long agentId) throws ExecutionException {
         Optional<WxPayService> wxPayServiceOptional =   this.wxPayServiceCache.get(agentId);
        if(wxPayServiceOptional.isPresent()){
            return wxPayServiceOptional.get();
        }else {
            return null;
        }
    }

}
